
import Query from './query.js'
import SuccessDialog from 'success_alert'
import ErrorDialog from 'error_alert'

var Util = {
  getUrlParameter: function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
    sURLVariables = sPageURL.split('&'),
    sParameterName,
    i;

    for (i = 0; i < sURLVariables.length; i++) {
      sParameterName = sURLVariables[i].split('=');

      if (sParameterName[0] === sParam) {
        return sParameterName[1] === undefined ? true : sParameterName[1];
      }
    }
  },

  uploadPhoto: function(e, postUrl, callback) {
    var _this = this
    let files = e.target.files || e.dataTransfer.files

    if (!files.length) {
      ErrorDialog.show('网络问题，请重新选择图片')
      return
    }

    if(typeof FileReader==='undefined'){
      ErrorDialog.show('您的浏览器不支持图片上传，请升级您的浏览器')
      return
    }

    let reader = new FileReader()
    reader.readAsDataURL(files[0])

    reader.onload = function(e){
      _this.photo = e.target.result
      Query.put(postUrl, {
        image: _this.photo
      }).then((data) => {
        if (data.flag) {
          SuccessDialog.show(data.message)
          if(callback) {
            callback.call(this, data.image_url)
          }
        } else {
          ErrorDialog.show(data.message)
        }
      }).catch((error) => {
        console.log(error)
      })
    }
  },
  common_ajax_post_for_html: function(url, data, successCallback, completeCallback, beforeCallback) {
    var self;
    self = this;
    return $.ajax({
      type: 'POST',
      url: url,
      data: $.extend(data, {
        authenticity_token: AUTH_TOKEN
      }),
      beforeSend: function() {
        if (beforeCallback) {
          return beforeCallback.call(self);
        }
      },
      complete: function() {
        if (completeCallback) {
          return completeCallback.call(self);
        }
      },
      success: function(data) {
        if (successCallback) {
          return successCallback.call(self, data);
        }
      }
    });
  },

  isIosDevice: function() {
    var iDevices = [
      'iPad Simulator',
      'iPhone Simulator',
      'iPod Simulator',
      'iPad',
      'iPhone',
      'iPod'
    ];

    if (!!navigator.platform) {
      while (iDevices.length) {
        if (navigator.platform === iDevices.pop()){ return true; }
      }
    }

    return false;
  },

  obj_to_params: function(obj) {
    return _.reduce(_.keys(obj), function(r, key) {
      if(obj[key][0])
        r += key+obj[key].join('_') +'-';
      return r;
    }, '').replace(/-$/, '');
  },

  obj_to_radio_params: function(obj) {
    return _.map(obj, function(value, key){return key+value}).join('-');
  },

  obj_to_query_params: function(object) {
    var obj = {};
    for(key in object) {
      if(!/^\w+_stack$/.test(key)){
        obj[key] = object[key];
      }
    }
    var result = '';
    for(key in obj) {
      if (_.isArray(obj[key])) {
        var newObject = {};
        newObject[key] = obj[key];
        var pending=Util.obj_to_params(newObject)
        if(pending != "")
          result += '-' + pending;
      } else {
        var newObject = {};
        newObject[key] = obj[key];
        var pending=Util.obj_to_radio_params(newObject)
        if(pending != "")
          result += '-'+ pending;
      }
    }
    return result.replace(/^-+/,'');
  },

  phoneToStart: function(mobile) {
    return mobile.substr(0, 3) + '****' + mobile.substr(7, 11);
  },

  productImg: function(product) {
    if (product && product.main_img_url) {
      return product.main_img_url
    } else {
      return 'http://oqhwiuu27.bkt.clouddn.com/default_product.png'
    }
  },

  load_jiathis: function() {
    let url = 'http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)
    let script = document.createElement('script')
    script.setAttribute('src', url)
    document.getElementsByTagName('head')[0].appendChild(script)

    window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}}
  }


}

module.exports = Util;
